package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hzy.lib7z.Z7Extractor;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.BuildConfig;
import com.ramos.kuaixiao.MyView.CircleImageView;
import com.ramos.kuaixiao.MyView.SelfDialog;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.MyGridAdapter;
import com.ramos.kuaixiao.network.DownloadClientPriceTask;
import com.ramos.kuaixiao.network.DownloadCustomerStoreTask;
import com.ramos.kuaixiao.network.DownloadCustomerTask;
import com.ramos.kuaixiao.network.DownloadEmpBrandTask;
import com.ramos.kuaixiao.network.DownloadEmpStorehouseTask;
import com.ramos.kuaixiao.network.DownloadKeyWordsTask;
import com.ramos.kuaixiao.network.DownloadOrderTask;
import com.ramos.kuaixiao.network.DownloadPriceTask;
import com.ramos.kuaixiao.network.DownloadPriceTypeTask;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.FileUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SelectPicPopupWindow;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.Executors;

public class UserFragment extends Fragment implements OnClickListener {
    private static String TAG = "UserFragment";
    private Context mContext;
    private View mRoot;
    private TextView mLoginName;
    private GridView mGridView;
    private CircleImageView mIcon;
    private SelectPicPopupWindow menuWindow;
    private File mCurrentPhotoFile;
    public static final int CODE_GALLERY_REQUEST = 0xa0;
    public static final int CODE_CAMERA_REQUEST = 0xa1;
    private Uri photoUri;
    public String mImagePath;
    private CommonLoading loading;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        container = (ViewGroup) mRoot.getParent();
        if (container != null) {
            container.removeView(mRoot);
        }
        return mRoot;
    }

    @SuppressLint("InflateParams")
    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        mContext = getActivity();
        mCurrentPhotoFile = new File(FileUtil.getCirclePath(mContext) + "0.png");
        mRoot = LayoutInflater.from(mContext).inflate(R.layout.fragment_user_new, null);
        mLoginName = (TextView) mRoot.findViewById(R.id.title_user);
        mIcon = (CircleImageView) mRoot.findViewById(R.id.ivUserHead);
        mIcon.setOnClickListener(this);
        if (Utils.isNetworkConnected(getActivity())) {
            getUserIcon();
        }
        mGridView = (GridView) mRoot.findViewById(R.id.gridview);
        mGridView.setAdapter(new MyGridAdapter(getActivity()));

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectItem(position);
            }
        });
    }

    private void getUserIcon() {
        try {
            String url = NetUtils.USER_PIC;
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(100000);
            // 创建请求参数的封装的对象
            RequestParams params = new RequestParams();
            params.put("userId", SharedPreference.getPreferString("id"));
            params.put("id", SharedPreference.getPreferString("id"));
            Log.d(TAG, "getUserIcon:" + url);
            client.get(url, params, new AsyncHttpResponseHandler() {
                // 执行post方法
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    try {
                        if (responseBody != null) {
                            String imagePath = Utils.getLogPath(mContext) + "icon.jpg";
                            Utils.byte2image(responseBody, imagePath);
                            Log.d(TAG, "mIcon" + imagePath);
                            File image = new File((imagePath));
                            if (image.exists()) {
                                mIcon.setImageBitmap(Utils.decodeFile(image));
                                //Utils.glideFile(new File((imagePath)), mIcon);
                                SharedPreference.setPreferString("headPic", imagePath);
                            }
                        } else {
                            getLocalIcon();
                        }
                    } catch (Exception e) {
                        getLocalIcon();
                        e.printStackTrace();
                    }
                }

                /**
                 * 失败处理的方法 error：响应失败的错误信息封装到这个异常对象中
                 */
                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    getLocalIcon();
                    error.printStackTrace();// 把错误信息打印出轨迹来
                }
            });
        } catch (Exception e) {
            getLocalIcon();
            loading.dismiss();
            e.printStackTrace();
        }
    }

    private void getLocalIcon() {
        try {
            if (SharedPreference.hasPreferString("headPic")) {
                File image = new File((SharedPreference.getPreferString("headPic")));
                if (image.exists()) {
                    mIcon.setImageBitmap(Utils.decodeFile(image));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        if (SharedPreference.hasPreferString("name")) {
            mLoginName.setText(SharedPreference.getPreferString("name"));
        }
    }

    private void selectItem(int position) {
        switch (position) {
            case 0:
                startActivity(new Intent(getActivity(), UserInfoActivity.class));
                break;
            case 1:
                startActivity(new Intent(getActivity(), UnSubmitOrderActivity.class));
                //startActivity(new Intent(getActivity(), CustomerActivity.class));
                break;
            case 2:
                //ToastUtils.showWarning();
                startActivity(new Intent(getActivity(), DataReportActivity.class));
                break;
            case 3:
                startActivity(new Intent(getActivity(), ModifyPhoneActivity.class));
                break;
            case 4:
                startActivity(new Intent(getActivity(), ModifyMailActivity.class));
                break;
            case 5:
                startActivity(new Intent(getActivity(), ModifyPswActivity.class));
                break;
            case 6:
                startActivity(new Intent(getActivity(), AboutUsActivity.class));
                break;
            case 7:
                ToastUtils.showWarning();
                /*if (Utils.isNetworkConnected(getActivity())) {
                    syncData();
                } else {
                    ToastUtils.show("请打开网络后重试！");
                }*/
                break;
            case 8:
                logout();
                break;
            default:
                break;
        }
    }

    private void syncData() {
        final SelfDialog builder = new SelfDialog(getActivity());
        builder.setTitle("数据更新");
        builder.setMessage("数据更新将删除原有的数据(不包含购物车、未完成订单),且需要1分钟的时间数据才能更新完成,请确认网络正常,是否确认更新？");
        builder.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                builder.dismiss();
            }
        });
        builder.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                updateData();
                loading = new CommonLoading(getActivity());
                loading.setLoadText("获取数据中...");
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //延迟30S执行的任务
                        loading.dismiss();
                    }
                }, App.DELAY_TIME);
                builder.dismiss();
            }
        });
        builder.show();
    }

    private void updateData() {
        File file = new File(FileUtil.getDataPath(App.mContext));
        if (file.exists()) {
            file.delete();
        }
        getZipFile();
    }

    private void getZipFile() {
        try {
            String url = NetUtils.GET_ZIP;
            Log.d(TAG, "getZipFile " + url);
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(120000);
            client.get(url, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String zipUrl = Utils.getZipFile(responseBody, FileUtil.getZipPath(App.mContext), BuildConfig.DOWNLOAD_NAME);
                        Log.d(TAG, "zipUrl" + zipUrl);
                        if (!StringUtil.isEmpty(zipUrl)) {
                            Log.d(TAG, "zipUrl:isNotEmpty" + zipUrl);
                            if (Z7Extractor.extractFile(zipUrl, FileUtil.getZipPath(mContext), null)) {
                                getData();
                                //new BrandInfoDB().clearShopMall();
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getData() {
        try {
            DownloadOrderTask product7 = new DownloadOrderTask();
            product7.executeOnExecutor(Executors.newCachedThreadPool());
            File dirFile = new File(FileUtil.getDataPath(App.mContext));
            File[] files = dirFile.listFiles();
            if (files.length > 0) {
                for (File file : files) {
                    Log.d(TAG, "file:" + file.getName() + " " + file.getAbsolutePath());
                    if (file.getName().equals("tbl_customer.csv")) {
                        DownloadCustomerTask product = new DownloadCustomerTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_customer_store.csv")) {
                        DownloadCustomerStoreTask product = new DownloadCustomerStoreTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_emp_brand.csv")) {
                        DownloadEmpBrandTask product = new DownloadEmpBrandTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_emp_storehouse.csv")) {
                        DownloadEmpStorehouseTask product = new DownloadEmpStorehouseTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_pricetype.csv")) {
                        DownloadPriceTypeTask product = new DownloadPriceTypeTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    }  else if (file.getName().equals("tbl_productprice.csv")) {
                        DownloadPriceTask product3 = new DownloadPriceTask();
                        product3.executeOnExecutor(Executors.newCachedThreadPool());
                    }  else if (file.getName().equals("tbl_so_org_customer_salesperson.csv")) {
                        DownloadClientPriceTask product10 = new DownloadClientPriceTask();
                        product10.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_stock.csv")) {
                        //库存表
                       /* DownloadStoreNumTask product4 = new DownloadStoreNumTask(2);
                        product4.executeOnExecutor(Executors.newCachedThreadPool());*/
                    }else if (file.getName().equals("tbl_brandkeywords.csv")) {
                        //品牌表
                        DownloadKeyWordsTask product = new DownloadKeyWordsTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void logout() {
        final SelfDialog builder = new SelfDialog(getActivity());
        builder.setTitle("账号登出");
        builder.setMessage("账号登出后，若登录账号改变，将会导致之前账号的部分数据被清空，重新加载新账号的数据；若账号不变，则不会改变数据。是否确认登出？");
        builder.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                builder.dismiss();
            }
        });
        builder.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                getActivity().finish();
                SharedPreference.clear();
                Toast.makeText(mContext, "登出成功！", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(getActivity(), LoginActivity.class));
                builder.dismiss();
            }
        });
        builder.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivUserHead:
                changeIcon();
                break;

            default:
                break;
        }
    }


    private void changeIcon() {
        this.menuWindow = new SelectPicPopupWindow(getActivity(), new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                menuWindow.dismiss();
                switch (paramAnonymousView.getId()) {
                    case R.id.pickPhotoBtn:
                        pickPhoto();
                        return;
                    case R.id.takePhotoBtn:
                        takePhoto();
                        return;
                    case R.id.cancelBtn:
                        menuWindow.dismiss();
                        return;
                    default:
                }
            }
        });
        menuWindow.showAtLocation(getActivity().findViewById(R.id.choose_layout), 81, 0, 0);
    }

    public void pickPhoto() {
        Intent localIntent = new Intent("android.intent.action.GET_CONTENT");
        localIntent.setType("image/*");
        startActivityForResult(localIntent, CODE_GALLERY_REQUEST);
    }

    public void takePhoto() {
        if (Environment.getExternalStorageState().equals("mounted")) {
            String fileDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
            SimpleDateFormat localObject2 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
            File imageFile = new File(fileDir, "/" + localObject2.format(new Date()) + ".jpg");
            try {
                photoUri = Uri.fromFile(imageFile);
                if (photoUri == null) {
                    photoUri = FileProvider.getUriForFile(
                            mContext,
                            "com.ramos.kuaixiao.fileprovider",
                            imageFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("takePhoto", "takePhoto " + imageFile.getAbsolutePath());
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra("output", photoUri);
            mImagePath = imageFile.getAbsolutePath();
            startActivityForResult(intent, CODE_CAMERA_REQUEST);
        } else {
            Toast.makeText(mContext, "内存卡不存在!", Toast.LENGTH_SHORT).show();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent paramIntent) {
        if (requestCode == CODE_GALLERY_REQUEST) {
            if (paramIntent == null) {
                return;
            } else {
                Log.d(TAG, "onActivityResult :: requestCode == PHOTO_WITH_DATA");
                ContentResolver resolver = mContext.getContentResolver();
                // 照片的原始资源地址
                Uri originalUri = paramIntent.getData();
                try {
                    Bitmap originalbitmap = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                    Log.d(TAG, "PHOTO_WITH_CAMERA originalbitmap" + originalbitmap.getByteCount());
                    showChooseImages(originalbitmap);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        if (requestCode == CODE_CAMERA_REQUEST) {
            Log.d(TAG, "onActivityResult :: requestCode == PHOTO_WITH_CAMERA");
            Glide.with(mContext).load(mImagePath).dontAnimate().centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(mIcon);
        }
        super.onActivityResult(requestCode, resultCode, paramIntent);
    }


    private void showChooseImages(Bitmap originalbitmap) {
        if (originalbitmap != null) {
            savePicture(originalbitmap);
        }
    }

    /**
     * 保存图片到本应用下
     **/
    @SuppressLint("SdCardPath")
    private void savePicture(Bitmap bitmap) {
        try {
            BufferedOutputStream localBufferedOutputStream = new BufferedOutputStream(
                    new FileOutputStream(mCurrentPhotoFile));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 10, localBufferedOutputStream);
            localBufferedOutputStream.flush();
            localBufferedOutputStream.close();
            updateIcon(mCurrentPhotoFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateIcon(File mCurrentPhotoFile) {
        try {
            String url = NetUtils.USER_PIC;
            loading = new CommonLoading(mContext);
            loading.setLoadText("更新头像中...");
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            /*PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
            client.setCookieStore(myCookieStore);*/
            // 创建请求参数的封装的对象
            client.setTimeout(100000);
            // 创建请求参数的封装的对象
            RequestParams params = new RequestParams();
            params.put("file", mCurrentPhotoFile);
            params.put("id", SharedPreference.getPreferString("id"));
            client.post(url, params, new AsyncHttpResponseHandler() {
                // 执行post方法
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    loading.dismiss();
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result " + result);
                        JSONObject user = new JSONObject(result);
                        if (user.getInt("status") == 200) {
                            sendMessagea(UPLOAD_SUCCESS, result);
                        } else {
                            sendMessagea(UPLOAD_FAIL, "修改异常");
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        sendMessagea(UPLOAD_FAIL, "修改异常");
                    }
                }

                /**
                 * 失败处理的方法 error：响应失败的错误信息封装到这个异常对象中
                 */
                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.d(TAG, "sendImages ： fail " + statusCode);
                    error.printStackTrace();// 把错误信息打印出轨迹来
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            sendMessagea(UPLOAD_FAIL, "登陆异常");
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    Utils.glideFile(mCurrentPhotoFile, mIcon);
                    ToastUtils.show("修改成功");
                    break;
                case UPLOAD_FAIL:
                    ToastUtils.show("修改失败，请重新尝试");
                    break;
                default:
                    break;
            }
        }
    };

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }
}
